package cn.jetpiece.cloud.joss.app.modular.storage.service;

import cn.hutool.core.io.IoUtil;
import cn.jetpiece.cloud.joss.app.config.properties.OssProperties;
import cn.jetpiece.cloud.joss.app.core.constant.OssConstants;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.parser.Ranges;

import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.StringReader;

@Slf4j
public abstract class AbstractJossClient implements JossClient {

    /**
     * 初始化连接客户端
     *
     * @param endpoint  网址
     * @param accessKey 公钥
     * @param secretKey 密钥
     */
    public AbstractJossClient(String endpoint, String accessKey, String secretKey) {

    }

    /**
     * 获取ranges头部
     *
     * @param request 请求信息
     * @return ranges
     */
    protected Ranges getRanges(HttpServletRequest request) {
        String rangeHeader = request.getHeader("Range");
        if (rangeHeader == null) {
            return null;
        }
        Ranges ranges;
        try {
            ranges = Ranges.parse(new StringReader(rangeHeader));
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return null;
        }
        if (OssConstants.RANGE_HEADER_UNITS.equals(ranges.getUnits())) {
            return ranges;
        }
        return null;
    }

    protected void copyIO(InputStream inputStream, OutputStream outputStream, Long contentLength) {
        try {
            IoUtil.copyByNIO(inputStream, outputStream, getBufferSize(contentLength), null);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        } finally {
            try {
                inputStream.close();
                outputStream.close();
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
        }
    }

    protected int getBufferSize(Long objectSize) {
        if (objectSize == null) {
            return OssProperties.getInstance().getMinBufferSize();
        }
        return Math.min(objectSize.intValue(), OssProperties.getInstance().getMaxBufferSize());
    }
}
